package cn.gary.oaserver.service.impl;

import cn.gary.oaserver.config.utils.MenuStreamUtil;
import cn.gary.oaserver.config.utils.RedisUtil;
import cn.gary.oaserver.entity.TMenu;
import cn.gary.oaserver.entity.TMenuRole;
import cn.gary.oaserver.mapper.TMenuRoleMapper;
import cn.gary.oaserver.params.MenuParams;
import cn.gary.oaserver.service.ITMenuRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gary
 * @since 2024-03-15
 */
@Service
public class TMenuRoleServiceImpl extends ServiceImpl<TMenuRoleMapper, TMenuRole> implements ITMenuRoleService {

    @Autowired
    MenuStreamUtil menuStreamUtil;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public boolean delMenuChildrenByRoleId(Integer roleId, Integer menuId) {
        Integer[] mids = baseMapper.getAllDelMenuId ( menuId );
        QueryWrapper<TMenuRole> qw = new QueryWrapper<> ( );
        qw.in ( "mid", mids ).and ( q -> q.eq ( "rid", roleId ) );
        if (this.remove ( qw )) {
            redisUtil.clearMenuListFromRedis ();
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Integer[] getRoleMenuById(Integer roleId) {

        return baseMapper.getRoleMenuById ( roleId);
    }


    @Override
    public List<TMenu> getRoleMenu() {
        return menuStreamUtil.getAllMenus ( );
    }

    @Override
    @Transactional
    public boolean insetMenuRole(MenuParams menuParams) {
        QueryWrapper<TMenuRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rid",menuParams.getRid ());
        baseMapper.delete ( queryWrapper );
        List<TMenuRole> list=new ArrayList<> ();
        for (Integer integer : menuParams.getMenuId ( )) {
            list.add ( new TMenuRole (integer,menuParams.getRid ()) );
        }
        System.out.println ( list );
        if (this.saveBatch ( list )){
            redisUtil.clearMenuListFromRedis ();
            return true;
        }else {
            return false;
        }
    }
}
